package com.yunduansing.demo.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.yunduansing.demo.model.common.CacheKeyPrefix;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCrypt;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class JwtTokenUtil {
    @Value("${login.user.expires}")
    private static long loginUserExpires;

    public static DecodedJWT parseToken(String token){
        return JWT.decode(token);
    }

    public static String generateToken(String username){
        String salt = BCrypt.gensalt();
        Algorithm algorithm = Algorithm.HMAC256(salt);
        Date date = new Date(System.currentTimeMillis()+loginUserExpires);  //设置过期时间
        var token = JWT.create()
                .withSubject(username)
                .withExpiresAt(date)
                .withIssuedAt(new Date())
                .sign(algorithm);
        return token;
    }
}
